# ——创建时间：2019.2.19——
# 需要密码登陆软件，登陆成功后跳转主界面
import base64
import datetime
import json
import sys

import requests
import rsa
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import qdarkstyle
import time

from ui.main_ui import Ui_MainWindow
from ui import start

sPubk = ''
# 登陆对话框
class DialogUI(QWidget):
    def __init__(self, parent=None):
        super(DialogUI, self).__init__(parent)

        self.setWindowTitle("登陆")
        # self.resize(350,150)
        # 输入密码框
        flo = QFormLayout()
        self.e1 = QLineEdit()
        BtnOk = QPushButton("  确   定   ")
        BtnCancel = QPushButton(" 取 消 ")
        BtnOk.clicked.connect(self.login)
        BtnCancel.clicked.connect(self.close)  # 点击取消关闭窗口
        self.e1.setEchoMode(QLineEdit.Password)  # 设置密码不可见
        self.e1.textChanged.connect(self.textchanged)
        self.e2 = QLineEdit()
        self.testb1 = QTextBrowser()

        flo.addRow("请输入用户名：", self.e2)
        flo.addRow("请输入密码：", self.e1)
        flo.addRow(BtnOk, BtnCancel)
        flo.addWidget(self.testb1)
        self.setLayout(flo)

    # 核对密码是否正确
    def textchanged(self, text):
        if text == "12345":
            self.close()  # 关闭登陆界面
            WindowShow.show()
            print("输入正确,跳转至主界面")

    # 与服务器通信获取sPubKey ,并发送验证用户名密码。获得相应权限
    def login(self):

        ''' TODO: 使用多线程来跑子程序，防止假死。
            QThread
            OR
            Thread
        '''
        self.testb1.append("开始检查网络状况...")
        pwd = self.e1.text()
        user = self.e2.text()
        print('{} : {}'.format(user, pwd))
        self.testb1.append('{} : {}'.format(user, pwd))
        """ 连接地址 """
        # 发送post请求
        remote = 'http://127.0.0.1:8090'
        # r1 = requests.post("",data={key:value})
        (pubk, prvk) = rsa.newkeys(1024);
        pub = pubk.save_pkcs1()
        print("pub:", pub)
        # base64加密。成字符串
        pub64 = str(base64.b64encode(pub), 'utf-8')
        print("pub64:", pub64)
        print('解密：')
        prv = prvk.save_pkcs1()
        d = datetime.datetime.now().strftime('%Y-%m-%d')
        c = rsa.encrypt(d.encode('utf-8'), pubk)
        print('登录与服务端建立连接')
        print('发送公钥。')
        headers = {
            "Content-Type": "application/json; charset=UTF-8",
        }
        data = json.dumps({"0": pub64})  # dumps：将python对象解码为json数据
        '''发送公钥
           接收服务端的公钥
        '''
        r1 = requests.post(remote+'/auth/serverPub', data=data,headers=headers)
        respon = r1.json()
        print('response:',respon)
        """保存此次服务器的密钥。"""
        global sPubk
        sPubKey = respon.get("data")
        print('sPubkey',sPubKey)
        print('接收密文')
        print('解密密钥')
        # m = hashlib.md5()
        # b = a.enconde(encoding='UTF-8')

# 主窗口

class WindowShow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(WindowShow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle('主窗口')
        self.setWindowIcon(QIcon('icon.png'))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    d = DialogUI()
    d.show()
    WindowShow = WindowShow()  # 生成主窗口的实例
    sys.exit(app.exec())
